<template>
    <div class="agency-detail">
        <a-modal width="1300px" :visible="visible" title="机构详情" @cancel="closeModal" class="yuan-modal activity-detail-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :class="isShow?'disable-form':''" :label-col="{ style: { width: '150px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">

                    <div class="form-panel yuan-form-col3">
                        <div class="form-panel-box">
                            <div class="form-title">活动信息</div>

                            <a-form-model-item class="yuan-form-item" label="活动名称" prop="name">
                                <a-input class="yuan-form-input" placeholder="活动名称" v-model="formData.name"></a-input>
                            </a-form-model-item>

                            <a-form-model-item label="活动海报" class="yuan-form-row" v-if="pageReady" prop="picture">
                                <UploadVue :uploadLength="1" @uploadChange="uploadChangeCoverImageUrl"
                                    :defImgList="formData.picture?[formData.picture]:[]" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-row" label="活动介绍" prop="description">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.description" placeholder="请输入活动介绍" :maxLength="500" />
                            </a-form-model-item>
                            <AgencyListVue ref="AgencyListVue" :defaltData="formData.couponStores" v-if="visible" :isShow="isShow"/>
                        </div>

                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <template v-if="isAudit">
                    <a-button @click="closeModal">
                        关闭
                    </a-button>
                    <a-button @click="clickPass" type="success" :loading="saveLoading">
                        通过
                    </a-button>
                    <a-button @click="clickRefuse" type="danger" :loading="saveLoading">
                        拒绝
                    </a-button>
                </template>
                <template v-else-if="isShow">
                    <a-button @click="closeModal">
                        关闭
                    </a-button>
                </template>
                <template v-else>
                    <a-button @click="modalOk" type="primary" :loading="saveLoading">
                        确认保存
                    </a-button>
                    <a-button @click="closeModal">
                        取消
                    </a-button>
                </template>

            </template>
        </a-modal>
        <a-modal width="600px" title="拒绝原因" :visible="refuseVisible" @ok="refuseOk" @cancel="()=>refuseVisible=false" okText="确定"
            cancelText="取消">
            <a-spin tip="Loading..." :spinning="refuseLoading">
                <a-form-model layout="inline" class="yuan-form" :label-col="{ style: { width: '100px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">

                        <a-form-model-item label="拒绝原因">
                            <a-input v-model="rejectCause" type="textarea" style="width: 500px;" :rows="5" placeholder="请输入拒绝原因"
                                :maxLength="500" />
                        </a-form-model-item>
                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import UploadVue from "@/components/upload.vue";
import platformApi from "@/api/platformApi";
import AgencyListVue from "./agencyList.vue";
import marketApi from "@/api/marketApi";
@Component({
    name: "tpl",
    components: { UploadVue, AgencyListVue },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: false }) isAudit!: boolean;
    @Prop({ default: "" }) editInfo!: any;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            if (this.editInfo.id) {
                this.getAgencyList();
            } else {
                this.formData = {};
                this.pageReady = true;
            }
        } else {
            this.pageReady = false;
        }
    }
    saveLoading = false;
    formData: any = {};
    rules = {
        name: [{ required: true, message: "请输入活动名称", trigger: "change" }],
        description: [{ required: true, message: "请输入活动介绍", trigger: "change" }],
    };
    pageReady = false;

    async mounted() {}

    closeModal() {
        this.$emit("closeModal");
    }
    async getAgencyList() {
        let couponStores: any[] = [];
        let len = this.editInfo.couponS.length;
        this.saveLoading = true;
        if (this.isShow) {
            this.editInfo.couponS.forEach(async (item) => {
                couponStores.push({
                    storeName: item.placeOrganizationName,
                    storeId: item.placeOrganizationId,
                    couponList: [{ name: item.name, id: item.id }],
                    couponSel: item.id,
                    participationStatus:item.participationStatus,
                    refuseCause:item.refuseCause
                });
            });
            this.saveLoading = false;
            this.formData = {
                ...this.editInfo,
                couponStores,
            };
            this.pageReady = true;
        } else {
            this.editInfo.couponS.forEach(async (item) => {
                const res = await marketApi.findCouponListByOrganizationId({
                    pageSize: 1000,
                    pageNum: 1,
                    organizationId: item.placeOrganizationId,
                    status: 4,
                });
                couponStores.push({
                    storeName: item.placeOrganizationName,
                    storeId: item.placeOrganizationId,
                    couponList: res.data,
                    couponSel: undefined,
                });
                len--;
                if (len <= 0) {
                    this.saveLoading = false;
                    this.formData = {
                        ...this.editInfo,
                        couponStores,
                    };

                    this.pageReady = true;
                }
            });
        }
    }
    async modalOk() {
        const couponStores = (this.$refs["AgencyListVue"] as any).getPageData();

        const find = couponStores.find((item) => {
            return item.couponSel === "" || !item.couponSel;
        });

        if (find) {
            this.$message.error(`请选择${find.storeName}参与的优惠券`);
            return;
        }

        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.saveLoading = true;
            try {
                const res = await platformApi.addActivity({
                    ...this.formData,
                    couponS: couponStores.map((item) => ({
                        couponId:item.couponSel,
                        organizationId:item.storeId
                    })),
                });
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }

    uploadChangeCoverImageUrl(e) {
        this.formData.picture = e.length ? e[0].url : "";
    }


    async clickPass() {
        this.$confirm({
            title: "确定要通过吗？",
            okText: "确定",
            cancelText: "取消",
            onOk: async () => {
                const res = await marketApi.jsActivityactivityAudit({
                    activityId: this.formData.id,
                    auditStatus: 1,
                    rejectReason: "",
                });
                this.$message.success(res.msg);
                this.closeModal();
                this.$emit("resetList");
            },
            onCancel: () => {
                console.log("Cancel");
            },
        });
    }
    refuseVisible = false;
    rejectCause = "";
    refuseLoading = false;
    clickRefuse() {
        this.refuseVisible = true;
    }
    async refuseOk() {
        this.refuseLoading=true
        const res = await marketApi.jsActivityactivityAudit({
            activityId: this.formData.id,
            auditStatus: 2,
            rejectReason: this.rejectCause,
        });
        this.refuseLoading=false
        this.refuseVisible=false
        this.$message.success(res.msg);
        this.closeModal();
        this.$emit("resetList");
    }
}
</script>
<style lang="scss">
.activity-detail-modal {
}
</style>
